package io.zhifei.modules.sys.pr.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zhifei.common.utils.ApiResponse;
import io.zhifei.common.utils.ExcelHead;
import io.zhifei.common.utils.ExecelUitl;
import io.zhifei.modules.sys.pr.entity.Student;
import io.zhifei.modules.sys.pr.service.DataCollectionService;
import io.zhifei.modules.sys.pr.mapper.DataCollectionMapper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 广告位表 服务实现类
 * </p>
 *
 * @author luoqiming
 * @since 2021-08-09
 */
@Service
public class DataCollectionServiceImpl extends ServiceImpl<DataCollectionMapper, io.zhifei.modules.sys.pr.entity.Student> implements DataCollectionService {

    @Override
    public ApiResponse findPageBySpec() {
        QueryWrapper<io.zhifei.modules.sys.pr.entity.Student> queryWrapper = new QueryWrapper<>();
        return new ApiResponse(this.baseMapper.selectList(queryWrapper));
    }

    @Override
    public ApiResponse addData(io.zhifei.modules.sys.pr.entity.Student student) {
        return new ApiResponse(this.baseMapper.insert(student));
    }

    @Override
    public ApiResponse dcAddList() {
        QueryWrapper<io.zhifei.modules.sys.pr.entity.Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        List<io.zhifei.modules.sys.pr.entity.Student> students = baseMapper.selectList(queryWrapper);
        List<Long> collect = students.stream().map(io.zhifei.modules.sys.pr.entity.Student::getId).collect(Collectors.toList());
        baseMapper.updateByStatus(collect);
        return new ApiResponse(students);
    }

    @Override
    public Object importCustomer(MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            List<ExcelHead> excelHeads = new ArrayList<>();
            //表单解析中文设置
            ExcelHead excelHead = new ExcelHead("姓名", "name");
            ExcelHead excelHead1 = new ExcelHead("年龄", "age");
            ExcelHead excelHead2 = new ExcelHead("手机号", "phone");
            ExcelHead excelHead3 = new ExcelHead("性别", "sex");
            excelHeads.add(excelHead);
            excelHeads.add(excelHead1);
            excelHeads.add(excelHead2);
            excelHeads.add(excelHead3);
            List<Student> list = ExecelUitl.readExcelToEntity(Student.class, in, file.getOriginalFilename(), excelHeads);
            for (Student batchImportEntity : list) {
                baseMapper.insert(batchImportEntity);
            }
            System.out.println(list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public Integer conversion(String str) {
        Student student = new Student();
        student.setName(str);
        return baseMapper.update(student, Wrappers.<Student>query().lambda().isNull(Student::getName).or().eq(Student::getName, ""));
    }

    @Override
    public ApiResponse copyList() {
        return new ApiResponse(baseMapper.copyList());
    }

    @Override
    public void merge() {
        baseMapper.merge();
        baseMapper.deleteCopy();
    }

    @Override
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Student> list = this.list();
        //sheet 最大行数
        final int sheetRowMax = 50000;
        //sheet 工作簿数量
        int sheetNum = 0;
        if (list != null) {
            sheetNum = list.size() % sheetRowMax == 0 ? list.size() / sheetRowMax : list.size() / sheetRowMax + 1;
        }
        //起始值
        int start = 0;
        //最大偏移量 如果大于最大限定行数则为 50000否则取最大数量
        int max = list.size() > sheetRowMax ? sheetRowMax : list.size();

        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();

        for (int i = 0; i < sheetNum; i++) {
            //更新起始值 和最大偏移量 如果 i = 2 , start = 50000 , max = i * 50000  +  start ....
            if (i > 0 && max >= sheetRowMax) {
                start = i * sheetRowMax;
                max = max + sheetRowMax < list.size() ? max + sheetRowMax : list.size();
            }

            String sheetName = "导出数据-" + i;
            String title = "导出数据";

            //建立新的sheet对象（excel的表单）
            HSSFSheet sheet = wb.createSheet(sheetName);
            //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
            HSSFRow row1 = sheet.createRow(0);
            //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
            HSSFCell cell = row1.createCell(0);
            //设置单元格内容
            cell.setCellValue(title);
            //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
            //在sheet里创建第二行
            HSSFRow row2 = sheet.createRow(1);
            //创建单元格并设置单元格内容
            row2.createCell(0).setCellValue("姓名");
            row2.createCell(1).setCellValue("年龄");
            row2.createCell(2).setCellValue("手机号");
            row2.createCell(3).setCellValue("性别");

            //行数
            int rowNum = 2;
            //在sheet里创建数据
            for (int j = start; j < max; j++) {
                Student student = list.get(j);
                HSSFRow row_x = sheet.createRow(rowNum);
                row_x.createCell(0).setCellValue(student.getName());
                row_x.createCell(1).setCellValue(student.getAge());
                row_x.createCell(2).setCellValue(student.getPhone());
                row_x.createCell(3).setCellValue(student.getAge());
                rowNum++;
            }
        }
        //输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=" + LocalDateTime.now() + ".csv");
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }

}
